package com.tang.campusyc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;

import com.tang.campusyc.data_claaback.TallDataCallBack;
import com.tang.campusyc.errorlog.ErrorGetActivity;
import com.tang.campusyc.toast.DiyDialog_Error_get;
import com.tang.campusyc.toast.DiyToast;

public class RegActivity extends Activity {
	private Button btn_mianze;
	private boolean isReadTrue = false;
	private Button btn_cls;
	private Button btn_con;
	private EditText et_euser, et_epass;
	private String euser, epass, tips = "";
	private ProgressDialog progressDialog;
	private boolean isTrue = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reg);
		btn_mianze = (Button) findViewById(R.id.btn_dialog_mianze);
		btn_cls = (Button) findViewById(R.id.btn_cls);
		btn_con = (Button) findViewById(R.id.btn_con);
		et_epass = (EditText) findViewById(R.id.et_reg_passward);
		et_euser = (EditText) findViewById(R.id.et_reg_username);
		BmobQuery<TallDataCallBack> bmobQuery = new BmobQuery<TallDataCallBack>();
		bmobQuery.getObject(RegActivity.this, "bb9a44a2a7",
				new GetListener<TallDataCallBack>() {

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						DiyToast.showToast(getApplicationContext(), arg1);
					}

					@Override
					public void onSuccess(TallDataCallBack arg0) {
						// TODO Auto-generated method stub
						tips = arg0.getAddress().toString();
					}
				});
		et_pass_edit();
		btn_con.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				progress_bar_show();
				euser = et_euser.getText().toString();
				epass = et_epass.getText().toString();
				if (euser.isEmpty() || epass.isEmpty()) {
					DiyToast.showToast(getApplicationContext(), "不能有空白项");
					progressDialog.dismiss();
				} else {
					if (isTelPhoneNumber(euser) == false) {
						DiyToast.showToast(getApplicationContext(), "失败，"
								+ euser + "这不是一个电话号码");
						progressDialog.dismiss();
					} else {
						if (isReadTrue) {
							if (isTrue) {
								final BmobUser bmobUser = new BmobUser();
								bmobUser.setUsername(euser);
								bmobUser.setPassword(epass);
								bmobUser.signUp(RegActivity.this,
										new SaveListener() {

											@Override
											public void onSuccess() {
												// TODO Auto-generated method
												// stub
												DiyToast.showToast(
														getApplicationContext(),
														"注册成功，请记住您的密码：" + epass);
												progressDialog.dismiss();
												new AlertDialog.Builder(
														RegActivity.this)
														.setMessage(
																"请记住您的ObjectID，用于找回密码，不可丢失！"
																		+ "\n"
																		+ String.valueOf(bmobUser
																				.getObjectId()))
														.setPositiveButton(
																"确定",
																new DialogInterface.OnClickListener() {
																	@Override
																	public void onClick(
																			DialogInterface dialog,
																			int which) {
																		// TODO
																		// Auto-generated
																		// method
																		// stub
																		Build bd = new Build();
																		String model = bd.MODEL;
																		ErrorGetActivity.errorlog_get = "主人！您的用户多了一个！她or他or它的ID是："
																				+ euser
																				+ "---objectID是："
																				+ bmobUser
																						.getObjectId()
																				+ "---设备是："
																				+ model;
																		startActivity(new Intent(
																				getApplicationContext(),
																				ErrorGetActivity.class));
																		finish();
																	}
																})
														.setTitle("重要信息")
														.setIcon(
																android.R.drawable.ic_dialog_alert)
														.show();
											}

											@Override
											public void onFailure(int arg0,
													String arg1) {
												// TODO Auto-generated method
												// stub
												DiyToast.showToast(
														getApplicationContext(),
														"出现错误，请查看弹出框内容");
												try {
													DiyDialog_Error_get
															.showDialog_QQ(
																	RegActivity.this,
																	"错误代码："
																			+ String.valueOf(arg0),
																	arg1, "取消");
												} catch (Exception e) {
													// TODO: handle exception
													DiyToast.showToast(
															getApplicationContext(),
															String.valueOf(e));
												}
												progressDialog.dismiss();
											}
										});
							} else {
								DiyToast.showToast(getApplicationContext(),
										"密码不足六位");
							}
						} else {
							DiyToast.showToast(getApplicationContext(),
									"请先查阅协议并同意（在右下角~）");
							progressDialog.dismiss();
						}
					}
				}
			}
		});
		btn_cls.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				// TallDataCallBack p2 = new TallDataCallBack();
				// p2.setName("lucky");
				// p2.setAddress("北京海淀");
				// p2.save(RegActivity.this, new SaveListener() {
				//
				// @Override
				// public void onSuccess() {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void onFailure(int arg0, String arg1) {
				// // TODO Auto-generated method stub
				//
				// }
				// });
			}
		});
		btn_mianze.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dialog_show();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_reg, menu);
		return true;
	}

	/**
	 * 手机号号段校验， 第1位：1； 第2位：{3、4、5、6、7、8}任意数字； 第3—11位：0—9任意数字
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isTelPhoneNumber(String value) {
		if (value != null && value.length() == 11) {
			Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8][0-9]\\d{8}$");
			Matcher matcher = pattern.matcher(value);
			return matcher.matches();
		}
		return false;
	}

	private void et_pass_edit() {
		et_epass.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				if (start >= 5) {
					isTrue = true;
				} else {
					isTrue = false;
				}
				Log.e("onTextChanged--------s", s.toString());
				Log.e("onTextChanged--------start", String.valueOf(start));
				Log.e("onTextChanged--------count", String.valueOf(count));
				Log.e("onTextChanged--------before", String.valueOf(before));
				Log.i("isTrue", String.valueOf(isTrue));
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				Log.e("before--------s", s.toString());
				Log.e("before--------start", String.valueOf(start));
				Log.e("before--------count", String.valueOf(count));
				Log.e("before--------after", String.valueOf(after));
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				Log.e("AFTER", s.toString());
			}
		});
	}

	private void dialog_show() {
		new AlertDialog.Builder(RegActivity.this)
				.setMessage(tips)
				.setPositiveButton("同意", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						isReadTrue = true;
					}
				})
				.setNegativeButton("不同意",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								DiyToast.showToast(getApplicationContext(),
										"似乎不同意就没有办法继续了呢.....");
								isReadTrue = false;
							}
						}).setTitle("免责条款")
				.setIcon(android.R.drawable.ic_menu_week).show();
	}

	private void progress_bar_show() {
		// TODO Auto-generated method stub
		progressDialog = new ProgressDialog(RegActivity.this);
		progressDialog.setMessage("正在加载......");
		progressDialog.show();
	}
}
